from django.db import transaction
from rest_framework import serializers
from goods.models import SKU, SKUSpecification, SPUSpecification, SpecificationOption, GoodsCategory


class SKUSpecificationSeriazier(serializers.ModelSerializer):
    spec_id = serializers.IntegerField()
    option_id = serializers.IntegerField()
    class Meta:
        model = SKUSpecification # SKUSpecification中sku外键关联了SKU表
        fields=("spec_id",'option_id')


class SKUSeriazlier(serializers.ModelSerializer):
    """
        SKU表序列化器
    """
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    category = serializers.StringRelatedField(read_only=True)
    category_id = serializers.IntegerField()
    specs = SKUSpecificationSeriazier(many=True)
    class Meta:
        # 指定根据那个模型类生成序列化器字段
        model = SKU
        # 指定那些字段生成
        fields = "__all__"
    def create(self, validated_data):
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                specs = validated_data['specs']
                del validated_data['specs']
                sku = SKU.objects.create(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.create(sku=sku, spec_id=spec['spec_id'], option_id=spec['option_id'])
            except:
                transaction.savepoint_rollback(save_point)
                raise serializers.ValidationError('保存数据失败')
            else:
                transaction.savepoint_commit(save_point)
                return sku

    def update(self, instance, validated_data):
        with transaction.atomic():
            save_point = transaction.savepoint()
            try:
                specs = validated_data['specs']
                del validated_data['specs']
                SKU.objects.filter(id=instance.id).update(**validated_data)
                for spec in specs:
                    SKUSpecification.objects.filter(sku=instance,spec_id=spec['spec_id']).update(option_id=spec['option_id'])

            except:
                transaction.savepoint_rollback(save_point)
                raise serializers.ValidationError('保存数据失败')
            else:
                transaction.savepoint_commit(save_point)
                return instance


class GoodsCategorySerializer(serializers.ModelSerializer):
    """
        商品分类序列化器
    """

    class Meta:
        # 指定根据那个模型类生成序列化器字段
        model = GoodsCategory
        # 指定那些字段生成
        fields = "__all__"


class OptionSerialzier(serializers.ModelSerializer):
    """
        规格选项序列化器
    """

    class Meta:
        # 指定根据那个模型类生成序列化器字段
        model = SpecificationOption
        # 指定那些字段生成
        fields = ('id', 'value')


class SPUSpecificationSerialzier(serializers.ModelSerializer):
    """
        SPU规格表
    """
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()
    # 关联的规格选项表
    options = OptionSerialzier(many=True)

    class Meta:
        # 指定根据那个模型类生成序列化器字段
        model = SPUSpecification
        # 指定那些字段生成
        fields = "__all__"